<template>
    <div class="mainBackground relative">
        <div class="flex jc-center">
            <side-bar :online="online"></side-bar>
            <chat-content ref="chatPart"></chat-content>
        </div>
    </div>
</template>

<script>
    import sideBar from './sideBar/SideBar';
    import chatContent from './content/ChatContent';
    import Vue from 'vue';

    export default {
        components: {
            'sideBar': sideBar,
            'chatContent': chatContent,
        },
        data() {
            return {
                online: 0,
            }
        },
        computed: {
            userData() {
                return this.$store.state.userData;
            },

            chatTarget() {
                return this.$store.state.chatTarget;
            }
        },
        provide() {
            return {
                updateChatMessage: this.updateChatMessage,
            }
        },
        methods: {
            init(data) {
                let {user, online} = data;
                if (!user) {
                    this.$emit('alert', '用户不存在');
                    this.$router.replace('/login');
                }
                this.online = online;
                this.updateLastMTime(user.currentMessages);
                this.$store.commit('updateUser', user);

                //获取侧边栏消息版块的active数组
                this.$store.commit('initMessageActive');
            },

            //把最后的时间更新为MM:SS，但似乎没什么必要，后面再改吧
            updateLastMTime(messages) {
                for (let item of messages) {
                    let time = item.content.mList[item.content.mList.length - 1].time;
                    let data = new Date(time);
                    item.content.mList[item.content.mList.length - 1]
                        .updatedTime = data.toISOString().slice(5, 10)
                        + ' ' + data.toTimeString().slice(0, 5);
                }
            },

            updateChatMessage(target) {
                let chatData = [];
                let chatMessage = [];
                // this.chatPart.messages = [];
                let cm = this.userData.currentMessages;
                for (let i = 0; i < cm.length; i++) {
                    if(cm[i].opposite._id === target) {
                        chatMessage = [...cm[i].content.mList];
                        chatData.mID = cm[i].content._id;
                        chatData.totalLength = cm[i].content.listLength;
                        chatData.mLimit = 15;
                        //清除未读
                        this.$store.commit('clearUnread', i);
                        this.$socket.emit('clearUnread', cm[i].content._id);
                    }
                }
                if (chatMessage.length > 0) {
                    let last = null;
                    for (let item of chatMessage) {
                        let date = new Date(item.time);
                        if (!last || (date - last) / 1000 > 60) {
                            item.updatedTime = date.toISOString().slice(5, 10)
                                + ' ' + date.toTimeString().slice(0, 5);
                        } else {
                            item.updatedTime = '';
                        }
                        last = date;
                    }
                } else {
                    chatData.totalLength = 0;
                    chatData.mLimit = 15;
                }
                this.$store.commit('updateChatMessage', chatMessage);
                this.$store.commit('updateChatData', chatData);

                //监听图片加载，加载完成后执行滚动条组件的update方法
                this.imgOnload(chatMessage);
                this.$nextTick(this.$refs.chatPart.initMessage);
            },

            imgOnload(mList) {
                let queue = [];
                for (let i = 0; i < mList.length; i++) {
                    if (mList[i].textType === 'img') {
                        queue.push(i);
                    }
                }
                this.$store.commit('updateChatMessageImgQueue', queue);
            },

            updateOnline(data) {
                this.online += data.num;
            },

            delMessage(mID) {
                for (let i = 0; i < this.userData.currentMessages.length; i++) {
                    if (this.userData.currentMessages[i].content._id === mID) {
                        this.$store.commit('delMessage');
                        break
                    }
                }
                // if (this.messageID === mID) {
                //     this.exitChat();
                // }
            },

            updateAvatar(res) {
                //到vuex中修改userData
                this.$store.commit('updateProfile', res);
                //消除头像修改状态
                this.$refs.profileSet.reset();
            }
        },
        created() {
            let flag = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
            if (flag) {
                this.$router.replace('/mobile');
            }

            const {io} = require('socket.io-client');
            const url = process.env.VUE_APP_SOCKET_URL || '/';
            Vue.prototype.$socket = io(url, {
                query: {
                    token: sessionStorage.token
                }
            });
            // this.$socket.on('disconnect', () => {
            //     alert('已登出');
            //     this.$router.replace('/login');
            // })

            // this.$socket.on('getOut', () => {
            //     alert('在其他环境中登录');
            //     sessionStorage.clear();
            //     this.$router.push('/login');
            // })

            this.$socket.on('initUser', this.init)

            this.$socket.on('updateOnline', this.updateOnline);

            this.$socket.on('delChatAccess', this.delMessage);

            this.$socket.on('updateAvatar', this.updateAvatar);
        },
        beforeDestroy() {
            this.$socket.disconnect();
        }
    }
</script>

<style scoped lang="scss">

</style>